/* The file is part of the Waff web framework.
 *
 * Copyright (c) 2011, Grzegorz Skorupa
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditionsare met:
 *
 * - Redistributions of source code must retain the above copyright notice, this list of conditions
 *   and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions
 *   and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * - Neither the name of the Grzegorz Skorupa nor the names of its contributors may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package pl.org.waff;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 *
 * @author greg
 */
public class DefaultUserManager implements UserManager {

    private static String userClassName;
    private static Properties properties;

    public void init(String userClassName, String applicationPrefix, Properties props) {
        this.userClassName = userClassName;
        this.properties = props;
        //TODO: get role names from property file
    }

    public boolean isUserLoggedIn() {
        return false;
    }

    public User getCurrentUser(HttpServletRequest request) {
        boolean store=false;
        User user;
        user = (User) request.getSession().getAttribute("waffuser");
        if (user == null) {
            try {
                user = (User) Class.forName(userClassName).newInstance();
            } catch (Exception e) {
                user = new WaffUser();
            }
            store=true;
        }
        if(request.getUserPrincipal() != null){
            if(!request.getUserPrincipal().getName().equals(user.getName())){
                user.setName(request.getUserPrincipal().getName());
                user.setLoggedIn(true);
                user.setRoles(properties.getProperty(user.getName()+".roles"));
                user.setEmail(properties.getProperty(user.getName()+".email"));
                user.setAlias(properties.getProperty(user.getName()+".alias"));
                user.setRegistered(true);
                store=true;
            }
        }else{
           user=new WaffUser(); 
           store=true;
        }
        if(store){
            request.getSession().setAttribute("waffuser", user);
        }
        return user;
    }

    public String createLoginURL(String destinationURL) {
        return UserServiceFactory.getUserService().createLoginURL(destinationURL);
    }

    public String createLoginURL(HttpServletRequest request) {
        UserService userService = UserServiceFactory.getUserService();
        String thisURL = request.getRequestURI();
        return userService.createLoginURL(thisURL);
    }

    public String createLogoutURL(String destinationURL) {
        return UserServiceFactory.getUserService().createLogoutURL(destinationURL);
    }

    public String createLogoutURL(HttpServletRequest request) {
        UserService userService = UserServiceFactory.getUserService();
        String thisURL = request.getRequestURI();
        return userService.createLogoutURL(thisURL);
    }

    //TODO: findUsers
    public List findUsers(String name, String email, String roles) {
        return new ArrayList();
    }

    public User getUser(String name, String password) {
        WaffUser user;
        try {
            user = new WaffUser();
            //if we want to get guest user
            if(name==null||password==null){
                return user;
            }
            int size = 0;
            size = Integer.parseInt(properties.getProperty("users.count"));
            String text;
            String userName;
            for (int i = 1; i <= size; i++) {
                userName = properties.getProperty("user." + i + ".name");
                
                if (userName != null && name.equals(userName)) {
                    text = properties.getProperty(userName+ ".password");
                    if (password.equals(text)) {
                        user.setName(userName);
                        user.setRoles(properties.getProperty(userName + ".roles"));
                        user.setEmail(properties.getProperty(userName + ".email"));
                        text=properties.getProperty(userName + ".alias");
                        if(text!=null&&text.length()>0){
                           user.setAlias(text); 
                        }else{
                            user.setAlias(userName);
                        }
                        user.setRegistered(true);
                        user.setLoggedIn(true);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            user = new WaffUser();
        }
        return user;
    }
    
}
